//
//  DDEditMineInfoViewController.m
//  DingDongZP
//
//  Created by zurich on 16/3/30.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

#import "DDEditMineInfoViewController.h"
#import "DDEditInfoCell.h"
#import "DDInfoEditViewController.h"
#import "DDAvatarPickerView.h"
#import "DDDefaultsAvatarView.h"
#import "DDUserInfoService.h"
#import <BlocksKit/UIActionSheet+BlocksKit.h>
#import "DDTextFieldEditViewController.h"
#import "DDTextViewEditViewController.h"
#import "DDCommonDataService.h"
#import "DDWorkExperience.h"
#import "CCImageGetter.h"
#import <ReactiveCocoa/ReactiveCocoa.h>

@interface DDEditMineInfoViewController ()
<UITableViewDelegate,
UITableViewDataSource,
UIActionSheetDelegate>

@property (strong, nonatomic) UITableView *editInfoTableView;
@property (strong, nonatomic) NSArray *titleArray;

@property (nonatomic, strong) NSArray *yearsArray;
@property (nonatomic, strong) NSArray *yearsIDArray;

@property (nonatomic, strong) DDUserInfoService *service;


@property (nonatomic, strong) DDUserInfoModel *userInfo;
@property (nonatomic, strong) DDCommonDataService *commonService;

@end

@implementation DDEditMineInfoViewController

- (DDUserInfoService *)service
{
    if (!_service) {
        
        _service = [[DDUserInfoService alloc] init];
    }
    return _service;
}

- (void) setModel:(DDUserInfoModel *)model {
    
    _model = model;
    _userInfo = model;
    
    //    [self.editInfoTableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    self.titleArray = @[@"姓名",@"性别",@"工作年限",@"微信号"];
    
    self.title = @"个人信息";
    
    self.editInfoTableView = [[UITableView alloc] init];
    self.editInfoTableView.delegate = self;
    self.editInfoTableView.dataSource = self;
    self.editInfoTableView.backgroundColor = [UIColor clearColor];
    self.editInfoTableView.backgroundView = nil;
    [self.view addSubview:_editInfoTableView];
    self.view.backgroundColor = COLOR_BACKGROUND_GRAY;
    
    self.editInfoTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    [self.editInfoTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    
    
    [self loadExperence];
}

//-(void) initKVO {
//    
//    RAC(<#TARGET, ...#>)
//}

- (void) setNav {
    
    WEAKSELF
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] bk_initWithTitle:@"保存" style:UIBarButtonItemStyleDone handler:^(id sender) {
        
        
        BOOL isacc = [weakSelf isSaveAll];
        if (isacc == true) {
            [weakSelf.navigationController popViewControllerAnimated:true];
        }
    }];
    
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (BOOL) isSaveAll {
    
    if (self.userInfo.name == nil) {
    
        [[LDShowHUB shareInstance] showErr:@"姓名未填写"];
        return false;
    } else if (self.userInfo.sex == nil) {
        
        [[LDShowHUB shareInstance] showErr:@"性别未填写"];
        return false;
    } else if (self.userInfo.experience == nil) {
        
        [[LDShowHUB shareInstance] showErr:@"工作年限未填写"];
        return false;
    } else if (self.userInfo.weixin == nil) {
        
        [[LDShowHUB shareInstance] showErr:@"微信未填写"];
        return false;
    }
    
    return true;
}

- (void) viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self setNav];
    [self.rdv_tabBarController setTabBarHidden:true animated:true];
}

- (void)loadExperence
{
    WEAKSELF
    
    [[LDCheckPublicInfo shareInstance] checkoutAllExperienceJobfinderEdit:^(NSArray<NSDictionary *> * _Nonnull data) {
        
        NSMutableArray *titleArr = [NSMutableArray array];
        NSMutableArray *title_IDArr = [NSMutableArray array];
        
        for (NSDictionary *dict in data) {
            
            [titleArr addObject:dict[@"experience_text"]];
            [title_IDArr addObject:dict[@"experience_id"]];
            
        }
        
        weakSelf.yearsArray = titleArr;
        weakSelf.yearsIDArray = title_IDArr;
        
    }];
}

- (void)loadUserInfo:(void (^)(void))callback
{
    
    WEAKSELF;
    [self.service queryUserInfo:^(DDUserInfoModel *model) {
        
        weakSelf.userInfo = model;
        
        [weakSelf.editInfoTableView reloadData];
        
        if (model)  {
            [weakSelf hideLoading];
        }
        else {
            [weakSelf showText:@"获取用户信息失败！"];
        }
        if (callback) {
            callback();
        }
    }];
}

- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.titleArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIndentifier = @"cell";
//    static NSString *headerCellIndentifier = @"headerCell";
    DDEditInfoCell *cell = nil;
//    if (indexPath.row == 0) {
//        cell = [tableView dequeueReusableCellWithIdentifier:headerCellIndentifier];
//        if (!cell) {
//            cell = (DDEditInfoCell *)[[[NSBundle mainBundle] loadNibNamed:@"DDEditInfoHeaderCell" owner:self options:nil] lastObject];
//        }
//        cell.headerImageView.image = [UIImage imageNamed:@"common_avatar"];
//        if (self.userInfo) {
//            NSString *url = [DDAPIGenerate imageURLWithPath:self.userInfo.logo];
//            [cell.headerImageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"common_avatar"] options:SDWebImageRefreshCached];
//        }
//    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if (!cell) {
            cell = (DDEditInfoCell *)[[[NSBundle mainBundle] loadNibNamed:@"DDEditInfoCell" owner:self options:nil] lastObject];
        }
        switch (indexPath.row) {
            case 0:
                cell.infoLabel.text = self.userInfo.name;
                [self setCellColor:cell andModel:self.userInfo.name];
                
                break;
            case 1:
                cell.infoLabel.text = self.userInfo.sex;
                [self setCellColor:cell andModel:self.userInfo.sex];
                
                
                break;
            case 2:
                cell.infoLabel.text = self.userInfo.experience;
                [self setCellColor:cell andModel:self.userInfo.experience];
                break;
            case 3:
                cell.infoLabel.text = self.userInfo.weixin;
                [self setCellColor:cell andModel:self.userInfo.weixin];
                break;
            default:
                break;
        }
//    }
    cell.titleLabel.text = self.titleArray[indexPath.row];
    cell.backgroundColor = [UIColor whiteColor];
    return cell;
}

-(void) setCellColor:(DDEditInfoCell *)cell andModel:(id)str {
    
    if (str == nil) {
        cell.titleLabel.textColor = COLOR_FONT_RED;
    } else {
        cell.titleLabel.textColor = COLOR_FONT_DARK_GRAY;
    }
}

- (CGFloat )tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (indexPath.row == 0) {
//        return 74.f;
//    }
    
    return 47.f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
//        case 0:
//            [self checkAvatar];
//            break;
        case 0:
            [self modifyName];
            break;
        case 1:
            [self moditySex];
            break;
        case 2:
            [self modifyWorkyears];
            break;
        case 3:
            [self modityWxNumber];
            break;
        case 4:
            
            break;
        default:
            break;
    }
}

#pragma mark - functions
+ (void)checkAvatar
{
//    WEAKSELF;
    DDAvatarPickerView *avatar = [DDAvatarPickerView instanciate];
    [avatar showWithAnimation:YES];
    
    avatar.didSelectAvatarType = ^(NSInteger type) {
        if (type == 2) {
            
            DDDefaultsAvatarView *defaults = [DDDefaultsAvatarView instanciate];
            [defaults showWithAnimation:YES];
            
            defaults.didGetImage = ^(UIImage *img) {
                
                UIImage *clipimg = [DDUtils handleImage:img withSize:CGSizeMake(640, 640)];
                [DDEditMineInfoViewController uploadImg:clipimg];
//                [weakSelf uploadImage:clipimg];
                
                
            };
        }
        
        else if (type == 0) {
            [[CCImageGetter sharedImageGetter] takePhoto];
            [CCImageGetter sharedImageGetter].callback = ^(UIImage *img) {
//                [weakSelf uploadImage:img];
                [DDEditMineInfoViewController uploadImg:img];
            };
        }
        
        else if (type == 1) {
            [[CCImageGetter sharedImageGetter] selectFromAlbum];
            [CCImageGetter sharedImageGetter].callback = ^(UIImage *img) {
//                [weakSelf uploadImage:img];
                [DDEditMineInfoViewController uploadImg:img];
            };
        }
    };
}


+ (void)uploadImg:(UIImage *) img {
    
    [[LDShowHUB shareInstance] showStaus:@"上传中"];
    [DDUserInfoService uploadLogo:img callback:^(BOOL succ) {
        
        if (succ) {
            
            [[LDShowHUB shareInstance] showSucc:@"头像上传成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_CATTLE_EDIT_PERSIONINFO object:nil];
        } else {
            [[LDShowHUB shareInstance] showErr:@"头像上传失败，请重试"];
        }
    }];
}

- (void)uploadImage:(UIImage *)img
{
    WEAKSELF
    [self showLoading];
    [self.service uploadLogo:img callback:^(BOOL succ) {
        
        [weakSelf hideLoading];
        if (succ) {
            [weakSelf loadUserInfo:^{
                [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_CATTLE_EDIT_PERSIONINFO object:weakSelf.userInfo];
            }];
            
            [[LDUserInfoNet sharedInstance] queryToken:^(NSString * _Nonnull data) {
                
            } failure:nil];
            
        } else {
            [weakSelf showText:@"头像上传失败，请重试"];
        }
    }];
}

- (void)modifyName
{
    DDTextFieldEditViewController *vc = [[DDTextFieldEditViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    vc.title = @"姓名";
    vc.value = self.userInfo.name;
    WEAKSELF;
    vc.block = ^(NSString *newName) {
        [weakSelf.service updateName:newName callback:^(BOOL succ) {
            if (succ) {
                weakSelf.userInfo.name = newName;
                [weakSelf.editInfoTableView reloadData];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_CATTLE_EDIT_PERSIONINFO object:weakSelf.userInfo];
                [DDLoginUserManager setAccountNamefirst:newName];
            }
        }];
    };
}

- (void)modityWxNumber
{
    DDTextFieldEditViewController *vc = [[DDTextFieldEditViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    vc.title = @"微信号";
    
    WEAKSELF
    vc.value = self.userInfo.weixin;
    vc.block = ^(NSString *newName) {
        [weakSelf.service updateWxNumber:newName callback:^(BOOL succ) {
            if (succ) {
                weakSelf.userInfo.weixin = newName;
                [weakSelf.editInfoTableView reloadData];
                [DDLoginUserManager setWeixin:newName];
            }
        }];
    };
}

- (void)moditySex
{
    UIActionSheet *act = [[UIActionSheet alloc] initWithTitle:@"设置性别" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"男", @"女", @"保密", nil];
    act.tag = 102;
    [act showInView:self.view];
    WEAKSELF
    act.bk_didDismissBlock = ^(UIActionSheet *act, NSInteger idx) {
        if (idx != act.cancelButtonIndex) {
            [self.service updateSex:idx+1 callback:^(BOOL succ) {
                
                if (succ) {
                    [weakSelf loadUserInfo:^{
                        [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_CATTLE_EDIT_PERSIONINFO object:weakSelf.userInfo];
                    }];
                    
                } else {
                    [weakSelf showToastOnCenter:@"性别修改失败"];
                }
            }];
        }
    };
}

- (void)modifyWorkyears {
    
    WEAKSELF
    [self showLDActionSheetView:@"设置工作年限" labHeight:nil labsTitleArr: _yearsArray selClosure:^(NSInteger index) {
        
        weakSelf.userInfo.experience = _yearsArray[index];
        [self.service updateWorkyear:_yearsIDArray[index] callback:^(BOOL succ) {
            
            [weakSelf.editInfoTableView reloadData];
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_CATTLE_EDIT_PERSIONINFO object:weakSelf.userInfo];
            
        }];
    }];
}

//            DDWorkExperience *work = [weakSelf.yearsArray objectAtIndex:idx-1];
//            [self.service updateWorkyear:work.experience_id callback:^(BOOL succ) {
//                if (succ) {
//
//                    weakSelf.userInfo.experience = work.experience_text;
//                    [weakSelf.editInfoTableView reloadData];
//
//                    [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_CATTLE_EDIT_PERSIONINFO object:weakSelf.userInfo];
//                }
//            }];




//    UIActionSheet *act = [[UIActionSheet alloc] initWithTitle:@"设置工作年限" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil];


//    for (NSString *exp in self.yearsArray) {
//
////        [act addButtonWithTitle:exp];
//    }

//    act.tag = 103;
//    [act showInView:self.view];
//
//    act.bk_didDismissBlock = ^(UIActionSheet *act, NSInteger idx) {
//        WEAKSELF
//        if (idx != act.cancelButtonIndex) {
//            DDWorkExperience *work = [weakSelf.yearsArray objectAtIndex:idx-1];
//            [self.service updateWorkyear:work.experience_id callback:^(BOOL succ) {
//                if (succ) {
//
//                    weakSelf.userInfo.experience = work.experience_text;
//                    [weakSelf.editInfoTableView reloadData];
//
//                    [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_CATTLE_EDIT_PERSIONINFO object:weakSelf.userInfo];
//                }
//            }];
//        }
//    };


- (DDCommonDataService *)commonService
{
    if (!_commonService){
        _commonService = [[DDCommonDataService alloc] init];
    }
    return _commonService;
}

+(void)setDefaultAvatar:(int)gender {
    
    UIImage *img = nil;
    if (gender == 0 ) {
        
        img = [UIImage imageNamed:@"b1"];
        
    } else {
        img = [UIImage imageNamed:@"c7"];
    }
    
    UIImage *clipimg = [DDUtils handleImage:img withSize:CGSizeMake(640, 640)];
    [DDUserInfoService uploadLogo:clipimg callback:^(BOOL succ) {
        
    }];
}

@end
